package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/connectivity"
	"google.golang.org/grpc/credentials/insecure"
	"sync"
	"zxs-micro-2/zxs-micro-proto/serverfindpb/serverfind"
	"zxs-micro-2/zxs-micro-serverfind-client/config"
)

var conn *grpc.ClientConn
var client serverfind.ServerFindServiceClient
var serverLock sync.Mutex
var selfId string

func InitServerFindClient() (string, error) {
	var err error
	redailServerFindServer()
	rsp, err := client.AddServer(context.Background(), &serverfind.AddServerRequest{
		ServerType: config.Cfg.ServerType,
		ServerPort: config.Cfg.ClientPort,
		Protocol:   config.Cfg.ClientProtocol,
	})
	if err != nil {
		return "", err
	}
	selfId = rsp.ServerId
	fmt.Println("自己的Id=", selfId)
	return selfId, nil
}

func redailServerFindServer() {
	serverLock.Lock()
	if conn != nil && conn.GetState() == connectivity.Ready {
		serverLock.Unlock()
		return
	}
	var err error
	conn, err = grpc.Dial(config.Cfg.ServerFindServiceAddr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(
			fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, "grpc.health.v1.Health")))
	if err != nil {
		panic(err)
	}
	client = serverfind.NewServerFindServiceClient(conn)
}

func GetSelfIpAddr(ctx context.Context) string {
	rsp, err := client.QueryServerListByIds(ctx, &serverfind.QueryServerListByIdsRequest{
		Ids: []string{selfId},
	})
	if err != nil {
		//todo...
		return ""
	}
	if rsp == nil || len(rsp.ServerList) == 0 {
		//todo...
		return ""
	}
	return rsp.ServerList[0].ServerIpAddr
}

func GetClient() serverfind.ServerFindServiceClient {
	return client
}

func ShutDown(ctx context.Context) {
	client.ServerDown(ctx, &serverfind.ServerDownRequest{
		ServerId: selfId,
	})
	conn.Close()
}
